package xp2p.global;

import java.io.IOException;
import java.net.Socket;

import net.jxta.socket.JxtaServerSocket;

/**
 * The Class Server.
 */
public class Server implements Runnable {
	private boolean _failure = false;
	private Object _sync;
	public static long msgId = 1;
	private ChannelProvider provider;

	public static long getMsgId()

	{
		return msgId++;
	}

	public Server(ChannelProvider provider) {
		this.provider = provider;
	}

	private Thread thread = null;
	private JxtaServerSocket listener = null;

	public void start() {
		thread = new Thread(this);
		thread.start();
	}

	public void stop() {
		thread.interrupt();
	}

	public void stopRun() {
		try {
			listener.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			listener = provider.getServerChannel(Statics.MyPeerID);
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}
		while (true) {
			Socket client;
			try {
				client = listener.accept();
				ClientHandler handler = new ClientHandler(client);
				Thread handlerThread = new Thread(handler);
				handlerThread.start();
			} catch (IOException e) {
				synchronized (_sync) {
					_failure = true;
				}
				try {
					listener.close();

				} catch (IOException e1) {
					e1.printStackTrace();
					return;
				}
			}
		}
	}

	public boolean wasFailure() {
		boolean result;
		synchronized (_sync) {
			result = _failure;
		}
		return result;
	}
}
